//
//  ZXTextView.m
//  ZXOCWeiBo
//
//  Created by mac on 15/12/6.
//  Copyright © 2015年 itcast. All rights reserved.
//

#import "ZXTextView.h"

@interface ZXTextView()

@property(nonatomic,weak)UILabel *palceHolderLabel;

@end


@implementation ZXTextView

//创建label
-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
        UILabel * palceHolderLabel = [[UILabel alloc]init];
        palceHolderLabel.numberOfLines = 0;
        
        [self addSubview:palceHolderLabel];
        
        self.palceHolderLabel = palceHolderLabel;
    }
    
    //监听文本的变化UITextViewTextDidChangeNotification文本是否有变化
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange) name:UITextViewTextDidChangeNotification object:nil];
    return self;
}

#pragma mark 系统的setFont方法
-(void)setFont:(UIFont *)font
{
    [super setFont:font];
    self.palceHolderLabel.font = font;
}

#pragma mark 文本的变化
-(void)textChange
{
    //当文本有变化的时候隐藏
    self.palceHolderLabel.hidden = self.text.length > 0;
}

-(void)setPlaceHolder:(NSString *)placeHolder
{
    _placeHolder = placeHolder;
    
    self.palceHolderLabel.text = placeHolder;
    self.palceHolderLabel.textColor = [UIColor darkGrayColor];
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    
    CGFloat labelW = self.w - 5*2;
    
    //计算字体尺寸
    NSMutableDictionary * att = [NSMutableDictionary dictionary];
    att[NSFontAttributeName] = self.palceHolderLabel.font;
 CGSize placeHolderSize = [self.placeHolder boundingRectWithSize:CGSizeMake(labelW, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:att context:nil].size;
    
    self.palceHolderLabel.frame = CGRectMake(5, 9, labelW, placeHolderSize.height);
}

-(void)dealloc
{
    //移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
